import pygame
import os
import sys

class MenuScreen:
    def __init__(self, game):
        self.game = game
        self.screen = game.screen
        self.width = game.width
        self.height = game.height
        self.username = game.username
        
        # 颜色定义
        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.gray = (230, 230, 230)
        self.light_gray = (240, 240, 240)
        self.apple_blue = (0, 122, 255)
        self.apple_light_blue = (88, 172, 255)
        
        # 字体
        pygame.font.init()
        FONT_PATH = 'C:\\Windows\\Fonts\\simsun.ttc'
        try:
            self.title_font = pygame.font.Font(FONT_PATH, 60)
            self.button_font = pygame.font.Font(FONT_PATH, 32)
            self.info_font = pygame.font.Font(FONT_PATH, 24)
        except:
            self.title_font = pygame.font.SysFont("simsun", 60)
            self.button_font = pygame.font.SysFont("simsun", 32)
            self.info_font = pygame.font.SysFont("simsun", 24)
        
        # 菜单按钮 - 进一步调整尺寸和间距
        self.button_width = 360  # 增加按钮宽度
        self.button_height = 60  # 增加按钮高度
        self.button_margin = 30  # 增加按钮间距
        self.buttons_start_y = self.height // 2 - 210  # 向上移动起始位置
        
        # 菜单选项
        self.menu_options = [
            "本地对战", 
            "联机对战", 
            "AI对战", 
            "排行榜", 
            "设置", 
            "退出游戏"
        ]
        
        # 创建按钮矩形
        self.buttons = []
        for i, option in enumerate(self.menu_options):
            button_rect = pygame.Rect(
                self.width // 2 - self.button_width // 2,
                self.buttons_start_y + i * (self.button_height + self.button_margin),
                self.button_width,
                self.button_height
            )
            self.buttons.append((button_rect, option))
        
        # 加载音效
        self.click_sound = None
        try:
            sound_path = os.path.join("sound", "down.mp3")
            if os.path.exists(sound_path):
                self.click_sound = pygame.mixer.Sound(sound_path)
        except:
            pass
            
        # 排行榜窗口状态
        self.show_ranking = False
        self.ranking_data = []
        
        # 排行榜窗口尺寸和位置
        self.ranking_window_width = 500
        self.ranking_window_height = 500
    
    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # 左键点击
                mouse_pos = pygame.mouse.get_pos()
                
                # 如果排行榜窗口正在显示，检查是否点击了关闭按钮
                if self.show_ranking:
                    # 计算排行榜窗口位置
                    window_x = self.width // 2 - self.ranking_window_width // 2
                    window_y = self.height // 2 - self.ranking_window_height // 2
                    
                    # 关闭按钮区域
                    close_x = window_x + self.ranking_window_width - 30
                    close_y = window_y + 20
                    close_button = pygame.Rect(close_x, close_y, 20, 20)
                    
                    if close_button.collidepoint(mouse_pos):
                        if self.click_sound:
                            self.click_sound.play()
                        self.show_ranking = False
                        print("关闭排行榜窗口")
                    return
                
                # 检查是否点击了任何按钮
                for button, option in self.buttons:
                    if button.collidepoint(mouse_pos):
                        if self.click_sound:
                            self.click_sound.play()
                        
                        # 处理不同的菜单选项
                        if option == "本地对战":
                            self.game.game_mode = "local"
                            self.game.switch_to_game()
                        elif option == "联机对战":
                            self.game.game_mode = "online"
                            # 切换到网络对战界面
                            self.game.switch_to_online_game()
                        elif option == "AI对战":
                            self.game.game_mode = "ai"
                            self.game.switch_to_game()
                        elif option == "排行榜":
                            # 显示排行榜
                            self.show_ranking_window()
                        elif option == "设置":
                            # 这里可以添加设置的逻辑
                            pass
                        elif option == "退出游戏":
                            pygame.quit()
                            sys.exit()
    
    def show_ranking_window(self):
        """显示排行榜窗口"""
        # 获取排行榜数据
        if hasattr(self.game, 'db_manager'):
            self.ranking_data = self.game.db_manager.get_ranking(10)  # 获取前10名
            if self.ranking_data:
                print(f"获取到排行榜数据: {len(self.ranking_data)} 条记录")
            else:
                print("未获取到排行榜数据")
                self.ranking_data = []
        else:
            print("数据库管理器不可用")
            self.ranking_data = []
            
        self.show_ranking = True
    
    def render(self):
        # 填充背景
        self.screen.fill(self.light_gray)
        
        # 绘制渐变背景
        for y in range(self.height):
            # 从顶部的浅灰色渐变到底部的白色
            color = (
                int(self.light_gray[0] * (1 - y/self.height) + self.white[0] * (y/self.height)),
                int(self.light_gray[1] * (1 - y/self.height) + self.white[1] * (y/self.height)),
                int(self.light_gray[2] * (1 - y/self.height) + self.white[2] * (y/self.height))
            )
            pygame.draw.line(self.screen, color, (0, y), (self.width, y))
        
        # 绘制标题 - 调整位置和样式
        title_text = self.title_font.render("五子棋", True, self.black)
        title_rect = title_text.get_rect(center=(self.width//2, 90))
        self.screen.blit(title_text, title_rect)
        
        # 绘制装饰线
        line_width = 200
        pygame.draw.line(
            self.screen,
            self.apple_blue,
            (self.width//2 - line_width//2, title_rect.bottom + 15),
            (self.width//2 + line_width//2, title_rect.bottom + 15),
            3
        )
        
        # 绘制用户信息
        user_text = self.info_font.render(f"欢迎, {self.username}", True, (80, 80, 80))
        user_rect = user_text.get_rect(right=self.width - 20, top=20)
        self.screen.blit(user_text, user_rect)
        
        # 绘制菜单按钮
        mouse_pos = pygame.mouse.get_pos()
        
        for button, option in self.buttons:
            # 检查鼠标是否悬停在按钮上
            if button.collidepoint(mouse_pos):
                button_color = self.apple_light_blue
            else:
                button_color = self.apple_blue
            
            # 为"退出游戏"按钮使用不同的颜色
            if option == "退出游戏":
                button_color = (220, 53, 69) if button.collidepoint(mouse_pos) else (220, 53, 69, 200)
            
            # 绘制按钮 - 添加阴影效果
            shadow_rect = button.copy()
            shadow_rect.x += 3
            shadow_rect.y += 3
            pygame.draw.rect(self.screen, (50, 50, 50), shadow_rect, 0, 15)
            
            # 绘制按钮主体
            pygame.draw.rect(self.screen, button_color, button, 0, 15)
            
            # 绘制按钮内部边框
            inner_rect = button.inflate(-6, -6)
            pygame.draw.rect(self.screen, (255, 255, 255), inner_rect, 1, 12)
            
            # 绘制按钮文本 - 所有按钮都有图标，统一向右偏移
            text = self.button_font.render(option, True, self.white)
            
            # 文本水平居中但稍微向右偏移，为左侧图标留出空间
            text_rect = text.get_rect(center=(button.centerx + 15, button.centery))
            self.screen.blit(text, text_rect)
            
            # 绘制图标（简单示例）- 为所有按钮添加图标
            icon_size = 24
            icon_margin = 50  # 增加图标与按钮左边缘的距离
            icon_x = button.x + icon_margin
            icon_y = button.center[1]
            
            if option == "本地对战":
                # 绘制简单的用户图标（圆形）
                pygame.draw.circle(self.screen, self.white, (icon_x, icon_y), icon_size//2, 2)
            elif option == "联机对战":
                # 绘制简单的网络图标（方形）
                pygame.draw.rect(self.screen, self.white, (icon_x - icon_size//2, icon_y - icon_size//2, icon_size, icon_size), 2, 5)
            elif option == "AI对战":
                # 绘制简单的AI图标（三角形）
                pygame.draw.polygon(self.screen, self.white, [
                    (icon_x - icon_size//2, icon_y - icon_size//2),
                    (icon_x + icon_size//2, icon_y - icon_size//2),
                    (icon_x, icon_y + icon_size//2)
                ], 2)
            elif option == "排行榜":
                # 绘制简单的排行榜图标（三条横线）
                for i in range(3):
                    y_offset = -icon_size//2 + i * (icon_size//2)
                    line_width = icon_size - i * 4
                    pygame.draw.line(
                        self.screen, 
                        self.white, 
                        (icon_x - line_width//2, icon_y + y_offset),
                        (icon_x + line_width//2, icon_y + y_offset),
                        2
                    )
            elif option == "设置":
                # 绘制简单的设置图标（齿轮）
                pygame.draw.circle(self.screen, self.white, (icon_x, icon_y), icon_size//2, 1)
                pygame.draw.circle(self.screen, self.white, (icon_x, icon_y), icon_size//4, 0)
            elif option == "退出游戏":
                # 绘制简单的退出图标（X）
                pygame.draw.line(
                    self.screen, 
                    self.white, 
                    (icon_x - icon_size//2, icon_y - icon_size//2),
                    (icon_x + icon_size//2, icon_y + icon_size//2),
                    2
                )
                pygame.draw.line(
                    self.screen, 
                    self.white, 
                    (icon_x - icon_size//2, icon_y + icon_size//2),
                    (icon_x + icon_size//2, icon_y - icon_size//2),
                    2
                )
        
        # 绘制底部版权信息
        try:
            footer_font = pygame.font.Font(FONT_PATH, 18)
        except:
            footer_font = pygame.font.SysFont("simsun", 18)
        footer_text = footer_font.render("© 2025 五子棋游戏", True, (150, 150, 150))
        footer_rect = footer_text.get_rect(center=(self.width//2, self.height - 20))
        self.screen.blit(footer_text, footer_rect) 
        
        # 如果排行榜窗口处于显示状态，绘制排行榜
        if self.show_ranking:
            self.render_ranking_window()
            
    def render_ranking_window(self):
        """绘制排行榜窗口"""
        # 绘制半透明背景
        s = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
        s.fill((0, 0, 0, 128))  # 半透明黑色
        self.screen.blit(s, (0, 0))
        
        # 绘制排行榜窗口
        window_x = self.width // 2 - self.ranking_window_width // 2
        window_y = self.height // 2 - self.ranking_window_height // 2
        
        # 绘制窗口背景
        pygame.draw.rect(self.screen, self.white, (window_x, window_y, self.ranking_window_width, self.ranking_window_height), 0, 15)
        pygame.draw.rect(self.screen, self.apple_blue, (window_x, window_y, self.ranking_window_width, self.ranking_window_height), 2, 15)
        
        # 绘制窗口标题
        title_text = self.button_font.render("排行榜", True, self.black)
        title_rect = title_text.get_rect(center=(self.width // 2, window_y + 30))
        self.screen.blit(title_text, title_rect)
        
        # 绘制关闭按钮
        close_x = window_x + self.ranking_window_width - 30
        close_y = window_y + 20
        pygame.draw.rect(self.screen, (220, 53, 69), (close_x, close_y, 20, 20), 0, 5)
        pygame.draw.line(self.screen, self.white, (close_x + 5, close_y + 5), (close_x + 15, close_y + 15), 2)
        pygame.draw.line(self.screen, self.white, (close_x + 5, close_y + 15), (close_x + 15, close_y + 5), 2)
        
        # 绘制表头
        header_y = window_y + 70
        col_widths = [100, 80, 80, 80, 80]
        headers = ["用户名", "胜场", "负场", "平局", "得分"]
        
        for i, header in enumerate(headers):
            x_pos = window_x + sum(col_widths[:i]) + 30
            header_text = self.info_font.render(header, True, self.black)
            self.screen.blit(header_text, (x_pos, header_y))
        
        # 绘制分隔线
        pygame.draw.line(
            self.screen,
            self.gray,
            (window_x + 20, header_y + 30),
            (window_x + self.ranking_window_width - 20, header_y + 30),
            1
        )
        
        # 绘制排行榜数据
        if not self.ranking_data:
            no_data_text = self.info_font.render("暂无排行数据", True, (100, 100, 100))
            no_data_rect = no_data_text.get_rect(center=(self.width // 2, self.height // 2))
            self.screen.blit(no_data_text, no_data_rect)
        else:
            for i, (username, wins, losses, draws, score) in enumerate(self.ranking_data):
                row_y = header_y + 50 + i * 40
                
                # 绘制排名
                rank_text = self.info_font.render(f"{i+1}", True, self.black)
                self.screen.blit(rank_text, (window_x + 20, row_y))
                
                # 绘制用户名和数据
                data = [username, str(wins), str(losses), str(draws), str(score)]
                for j, value in enumerate(data):
                    x_pos = window_x + sum(col_widths[:j]) + 30
                    
                    # 为前三名添加特殊颜色
                    text_color = self.black
                    if i == 0:
                        text_color = (255, 215, 0)  # 金色
                    elif i == 1:
                        text_color = (192, 192, 192)  # 银色
                    elif i == 2:
                        text_color = (205, 127, 50)  # 铜色
                    
                    value_text = self.info_font.render(value, True, text_color)
                    self.screen.blit(value_text, (x_pos, row_y)) 